#!/bin/bash
set -x
DT="data_miner"
REMOTEDIR=/home/work/changsha_project/mining_data
DATADIR=/home/dig/graph_data/algorithm_data/changsha
CONSISTENCE_FILE="cs_file_md5.txt"
REMOTE_ADDR=172.18.180.228

if [ ! -d ${DATADIR}/${DT} ]; then
    echo "data not ready"
    exit 0;
fi

# 计算md5
cd ${DATADIR}/${DT}
cs_md5=`ls -Rlt |md5sum |  awk '{print $1}'`

old_cs_md5=''
if [ -f ${DATADIR}/${CONSISTENCE_FILE} ]; then
    old_cs_md5=`cat ${DATADIR}/${CONSISTENCE_FILE}`
fi

if [ "$cs_md5" == "$old_cs_md5" ]; then
    echo "version is the same,exit: md5 = ${cs_md5}"
    exit 0
fi

echo "当前MD5: ${cs_md5}"
echo "旧版MD5: ${old_cs_md5}"


cd ${DATADIR}
rm -rf ${DT}.tgz
tar -zcf ${DT}.tgz ${DT}

# 压缩文件计算md5
tar_md5=`cat ${DT}.tgz | md5sum | awk '{print $1}'`


try_cnt=0
while [ ${try_cnt} -lt 4 ];
do
    scp  ${DT}.tgz work@${REMOTE_ADDR}:${REMOTEDIR}/
    result=`ssh work@${REMOTE_ADDR} "sh" ${REMOTEDIR}"/cat_cs_md5.sh"`
    if [ "$tar_md5" != "$result" ];then
        echo "sync file failed"
    else
        # 发送MD5文件
        ssh work@${REMOTE_ADDR} "echo ${tar_md5} > ${REMOTEDIR}/${DT}.md5"
        break
    fi
    try_cnt=`expr ${try_cnt} + 1`
    if [ ${try_cnt} -ge 4 ];then
        echo "mining 数据传输失败了: ${DT}.tgz"
        exit -1
    fi
done

ssh work@${REMOTE_ADDR} "sh" ${REMOTEDIR}"/upload_mining_data_to_changsha.sh"
echo -n ${cs_md5} > ${DATADIR}/${CONSISTENCE_FILE}